import Taro, {Component, Config} from '@tarojs/taro';
import {Picker, View} from '@tarojs/components';
import './index.scss';
import {HxPost} from '../../service/http';
import shareImg from '../../assets/img/share.png';
import {
    AtButton, AtInputNumber,
    AtSegmentedControl
} from 'taro-ui';
import {getDateAfterDay, getFormatDate, getJsonKeyByKey, timePipe, timeWeekPipe} from '../../utils/utils';
import HxInfiniteScroll from '../../components/hxInfiniteScroll/hxInfiniteScroll';
import HxPage from '../../components/hxPage/hxPage';
import {hxParam} from "../../config/hx-param";

export default class OrderFood extends Component<any, any> {
    private pageNo = 1;
    private pageSize = 10;
    private canClick = true;
    private hasMore = false;

    constructor() {
        super();
        this.state = {
            current: 1,
            cardId: '',
            orderList: [],
            toggleIndex: -1,
            startDate: '',
            endDate: '',
            menuDate: '请选择',
            storeList: [],
            storeListOrigin: [],
            storeSelect: '请选择',
            mealTimeList: [],
            mealTimeListOrigin: [],
            mealSelect: '请选择',
            foodList: [],
            selectFoodNum: -1,
            quantity: 1,
            maxQuantity: 1,
            menuHeadList: [],
            showItem: null,
        };
    }

    // noinspection JSUnusedGlobalSymbols
    onShareAppMessage() {
        return {
            title: '广州二中一卡通充值缴费',
            path: '/pages/personCenter/index',
            imageUrl: shareImg
        };
    }

    onDateChange(index, data) {
        let nowDate = data.target.value;
        if (index === 1) {
            if (nowDate != this.state['startDate']) {
                this.setState({
                    startDate: nowDate
                });
            }
        } else {
            if (nowDate != this.state['endDate']) {
                this.setState({
                    endDate: nowDate
                });
            }
        }
    }

    config: Config = {
        // navigationBarTitleText: '缴费列表'
        navigationBarTitleText: ''
    };

    changeTab(e) {
        this.pageNo = 1;
        this.setState({current: e});
        if (e === 0) {
            this.setState({
                startDate: getFormatDate(),
                endDate: getDateAfterDay(30),
            });
            this.getListInit();
        } else if (hxParam.isMealCater) {
            this.setState({
                startDate: getFormatDate(),
                endDate: getDateAfterDay(30),
            });
            this.getListInit();
        } else {
            this.getOrderList();
        }
    }

    getOrderList() {
        this.setState({
            menuDate: '请选择',
            storeList: [],
            storeListOrigin: [],
            storeSelect: '请选择',
            mealTimeList: [],
            mealTimeListOrigin: [],
            mealSelect: '请选择',
            foodList: [],
            selectFoodNum: -1,
            quantity: 1,
            menuHeadList: [],
        });
        Taro.showLoading({title: '加载中...', mask: true})
            .then(() => {
                return HxPost('orderFoodListAll', {cardId: this.state['cardId']});
            })
            .then((res: any) => {
                Taro.hideLoading();
                this.setState({
                    menuHeadList: res.menuHeadList,
                });
            })
            .catch((err) => {
                Taro.hideLoading();
                Taro.showToast({title: err.retMsg || '未知错误', icon: 'none', duration: 3 * 1000}).catch();
            });
    }

    // noinspection JSUnusedGlobalSymbols
    componentDidShow(): void {
        Taro.getStorage({key: 'cardId'})
            .then((res: any) => {
                if (res.data !== '') {
                    this.setState({
                        cardId: JSON.parse(res.data).cardId
                    });
                    this.changeTab(1);
                } else {
                    Taro.switchTab({
                        url: '/pages/personCenter/index'
                    })
                        .then(() => {
                            Taro.showToast({title: '请先绑定卡片', icon: 'none', duration: 3 * 1000});
                        }).catch();

                }
            });
    }

    getListInit() {
        this.pageNo = 1;
        this.setState({
            orderList: [],
            toggleIndex: -1,
        });
        this.getList();
    }

    getList() {
        this.hasMore = false;
        Taro.showLoading({title: '加载中...', mask: true})
            .then(() => {
                let param = {
                    cardId: this.state['cardId'],
                    pageNo: this.pageNo,
                    pageSize: this.pageSize,
                    startDate: this.state['startDate'].split('-').join(''),
                    endDate: this.state['endDate'].split('-').join(''),
                };
                return HxPost('orderFoodList', param);
            })
            .then((res: any) => {
                Taro.hideLoading();
                if (res['orderList'] && res['orderList'].length > 0) {
                    this.setState({
                        orderList: this.state['orderList'].concat(res['orderList'])
                    });
                    if (res['orderList'].length == this.pageSize) {
                        this.pageNo += 1;
                        this.hasMore = true;
                    }
                } else {
                    Taro.showToast({title: '未查询到更多订餐记录', icon: 'none', duration: 3 * 1000}).catch();
                }
            })
            .catch((err) => {
                Taro.hideLoading();
                Taro.showToast({title: err.retMsg || '未知错误', icon: 'none', duration: 3 * 1000}).catch();
            });
    }

    cancelOrder(orderList, index) {
        this.orderFood(orderList[index], 'D')
            .then(() => {
                orderList.splice(index, 1);
                this.setState({
                    orderList: orderList
                });
            })
            .catch(() => {
            });
    }

    toggleDetail(index) {
        this.setState({
            toggleIndex: this.state['toggleIndex'] === index ? -1 : index
        });
    }

    orderFood(item, action) {
        let msg = '确定预订餐吗？';
        if (action === 'M') {
            msg = '确定修改订餐吗？';
        }
        if (action === 'D') {
            msg = '确定退订该笔订餐吗？';
        }
        return Taro.showModal({
            title: '',
            content: msg,
            showCancel: true,
            cancelText: '取消',
            confirmText: '确定'
        })
            .then((res) => {
                if (res.confirm) {
                    return Taro.showLoading({title: '加载中...', mask: true});
                } else {
                    return Promise.reject('cancel');
                }
            })
            .then(() => {
                return HxPost('orderFood', {
                    menuDate: action === 'A' ? this.state['menuDate'].split('-').join('') : item['menuDate'],
                    cardId: this.state['cardId'],
                    storeId: action === 'A' ? getJsonKeyByKey(this.state['storeListOrigin'], 'storeId', 'storeName', this.state['storeSelect']) : item['storeId'],
                    mealTimeId: action === 'A' ? getJsonKeyByKey(this.state['mealTimeListOrigin'], 'mealTimeId', 'mealTimeName', this.state['mealSelect']) : item['mealTimeId'],
                    packageId: item['packageId'],
                    quantity: item['quantity'],
                    mealOrderId: action === 'A' ? '' : item['mealOrderId'],
                    opFlag: action
                });
            })
            .then((res: any) => {
                Taro.hideLoading();
                if (action === 'A') {
                    item.amountQuantity = Number(item.amountQuantity) + Number(item.quantity);
                    let newFoodList = this.state['foodList'];
                    let selectNum = this.state['selectFoodNum'];
                    newFoodList[selectNum].amountQuantity = item.amountQuantity;
                    this.setState({
                        foodList: newFoodList,
                        selectFoodNum: -1,
                        maxQuantity: Number(item.tatolQuantity) - Number(item.amountQuantity)
                    });
                }
                Taro.showToast({title: res.retMsg, icon: 'none', duration: 3 * 1000}).catch();
                return Promise.resolve();
            })
            .catch((err) => {
                if (err !== 'cancel') {
                    Taro.hideLoading();
                    Taro.showToast({title: err.retMsg || '未知错误', icon: 'none', duration: 3 * 1000}).catch();
                }
                return Promise.reject(err);
            });
    }


    modifyQuantity(item, e) {
        if (this.canClick) {
            this.canClick = false;
            let param = Object.assign({}, item);
            item.quantity = e;
            this.orderFood(item, 'M')
                .then(() => {
                    this.canClick = true;
                    this.setState({});
                })
                .catch(() => {
                    item.quantity = param.quantity;
                    this.canClick = true;
                    this.setState({});
                });
        }
    }

    goDetail(date, param, index) {
        let url = `/pages/orderFoodDetail/index?cardId=${this.state['cardId']}&date=${date}&index=${index}&param=${JSON.stringify(param)}`
        Taro.navigateTo({
            url: url
        }).catch();
    }

    showDetail(itemOrder) {
        this.setState({
            showItem: itemOrder
        })
    }

    render() {
        const {
            current,
            orderList,
            toggleIndex,
            startDate,
            endDate,
            menuHeadList,
            showItem,
        } = this.state;
        const isCatering = hxParam.isMealCater;
        return (
            <HxPage>
                {
                    showItem &&
                    <View className='my_dialog' onClick={this.showDetail.bind(this, null)}>
                        <View className='my_dialog_wrap'/>
                        <View className='my_dialog_main'>
                            <View className='my_dialog_main_header'>
                                {showItem.packageName} <View>¥{showItem.price}</View>
                            </View>
                            <View className='my_dialog_main_footer'>
                                {showItem.dishDetail}
                            </View>
                        </View>
                    </View>
                }
                <View className="orderFood">
                    <View className="orderFood_header">
                        <AtSegmentedControl
                            values={['订餐列表', isCatering ? '退餐记录' : '预订餐']}
                            selectedColor="#b71120"
                            fontSize={36}
                            onClick={this.changeTab.bind(this)}
                            current={current}
                        />
                    </View>
                    {
                        current === 0 ?
                            <View className="orderFood_scroll">
                                <View className="time_wrap">
                                    <View className="time_item">
                                        <Picker mode="date"
                                                fields="day"
                                                onChange={this.onDateChange.bind(this, 1)}
                                                value={startDate}
                                        >
                                            <View className="hxPicker">{startDate}</View>
                                        </Picker>
                                    </View>
                                    <View className="time_item">
                                        <Picker mode="date"
                                                fields="day"
                                                onChange={this.onDateChange.bind(this, 2)}
                                                value={endDate}
                                        >
                                            <View className="hxPicker">{endDate}</View>
                                        </Picker>
                                    </View>
                                    <View className="time_item">
                                        <AtButton className="hxButton sm_button"
                                                  onClick={this.getListInit.bind(this)}
                                        >确定</AtButton>
                                    </View>
                                </View>
                                <HxInfiniteScroll
                                    hasMore={this.hasMore}
                                    Upper={this.getList.bind(this)}
                                    Lower={this.getListInit.bind(this)}>
                                    <View className="orderFood_list">
                                        {
                                            orderList.map((item, index) => (
                                                <View key={index} className="orderFood_list_item">
                                                    <View className="orderFood_list_item_wrap">
                                                        <View className="orderFood_list_item_con">
                                                            {timePipe(item.menuDate, 'MM-DD')}
                                                        </View>
                                                        <View className="orderFood_list_item_con">
                                                            {item.mealTimeName}
                                                        </View>
                                                        <View className="orderFood_list_item_con">
                                                            {item.packageName}
                                                        </View>
                                                        <View className="orderFood_list_item_con">
                                                            {item.takeAddr}
                                                        </View>
                                                        <View className="orderFood_list_item_con">
                                                            <AtButton className="hxButton xs_button"
                                                                      onClick={this.toggleDetail.bind(this, index)}
                                                            >
                                                                {toggleIndex === index ? '收起' : '详情'}
                                                            </AtButton>
                                                        </View>
                                                    </View>

                                                    <View
                                                        hidden={toggleIndex !== index}
                                                        className="orderFood_list_detail">
                                                        <View className="orderFood_list_detail_wrap">
                                                            <View className="orderFood_list_detail_con">
                                                                日期：{timePipe(item.menuDate)}
                                                            </View>
                                                            <View className="orderFood_list_detail_con">
                                                                餐次：{item.mealTimeName}
                                                            </View>
                                                        </View>
                                                        <View className="orderFood_list_detail_con">
                                                            食堂： {item.storeName}
                                                        </View>
                                                        <View className="orderFood_list_detail_wrap">
                                                            <View className="orderFood_list_detail_con">
                                                                套餐名称：{item.packageName}
                                                            </View>
                                                            <View className="orderFood_list_detail_con">
                                                                取餐点：{item.takeAddr}
                                                            </View>
                                                        </View>
                                                        <View className="orderFood_list_detail_con">
                                                            菜品明细：{item.dishDetail}
                                                        </View>
                                                        <View className="orderFood_list_detail_footer">
                                                            <View className="orderFood_list_detail_footer_amount">
                                                                ¥{item.price.toFixed(2)} x
                                                                <View
                                                                    className="orderFood_list_detail_footer_amount_wrap">
                                                                    <View
                                                                        className="orderFood_list_detail_footer_amount_wrap_son"/>
                                                                    <AtInputNumber
                                                                        type="digit"
                                                                        min={1}
                                                                        max={100}
                                                                        step={1}
                                                                        value={item.quantity}
                                                                        disabled={item.isModify === 'N' || !this.canClick}
                                                                        onChange={this.modifyQuantity.bind(this, item)}
                                                                    />
                                                                </View>
                                                            </View>
                                                            {
                                                                item.isModify === 'Y' ?
                                                                    <AtButton
                                                                        className="orderFood_list_detail_footer_button"
                                                                        onClick={this.cancelOrder.bind(this, orderList, index)}
                                                                    >退订</AtButton>
                                                                    :
                                                                    <View>
                                                                        已取餐份数：<View
                                                                        className="orderFood_list_detail_footer_takeCnt"
                                                                    >{item.takeCnt}</View>
                                                                    </View>
                                                            }
                                                        </View>
                                                    </View>
                                                </View>
                                            ))
                                        }
                                    </View>
                                </HxInfiniteScroll>

                            </View>
                            :
                            isCatering ?
                                <View className="orderFood_scroll">
                                    <View className="time_wrap">
                                        <View className="time_item">
                                            <Picker mode="date"
                                                    fields="day"
                                                    onChange={this.onDateChange.bind(this, 1)}
                                                    value={startDate}
                                            >
                                                <View className="hxPicker">{startDate}</View>
                                            </Picker>
                                        </View>
                                        <View className="time_item">
                                            <Picker mode="date"
                                                    fields="day"
                                                    onChange={this.onDateChange.bind(this, 2)}
                                                    value={endDate}
                                            >
                                                <View className="hxPicker">{endDate}</View>
                                            </Picker>
                                        </View>
                                        <View className="time_item">
                                            <AtButton className="hxButton sm_button"
                                                      onClick={this.getListInit.bind(this)}
                                            >确定</AtButton>
                                        </View>
                                    </View>
                                    <HxInfiniteScroll
                                        hasMore={this.hasMore}
                                        Upper={this.getList.bind(this)}
                                        Lower={this.getListInit.bind(this)}>
                                        <View className="orderFood_list">
                                            {
                                                orderList.map((item, index) => (
                                                    <View key={index} className="orderFood_list_item">
                                                        <View className="orderFood_list_item_wrap">
                                                            <View className="orderFood_list_item_con">
                                                                {timePipe(item.menuDate, 'MM-DD')}
                                                            </View>
                                                            <View className="orderFood_list_item_con">
                                                                {item.mealTimeName}
                                                            </View>
                                                            <View className="orderFood_list_item_con">
                                                                {item.packageName}
                                                            </View>
                                                            <View className="orderFood_list_item_con">
                                                                {item.takeAddr}
                                                            </View>
                                                            <View className="orderFood_list_item_con">
                                                                <AtButton className="hxButton xs_button"
                                                                          onClick={this.toggleDetail.bind(this, index)}
                                                                >
                                                                    {toggleIndex === index ? '收起' : '详情'}
                                                                </AtButton>
                                                            </View>
                                                        </View>

                                                        <View
                                                            hidden={toggleIndex !== index}
                                                            className="orderFood_list_detail">
                                                            <View className="orderFood_list_detail_wrap">
                                                                <View className="orderFood_list_detail_con">
                                                                    日期：{timePipe(item.menuDate)}
                                                                </View>
                                                                <View className="orderFood_list_detail_con">
                                                                    餐次：{item.mealTimeName}
                                                                </View>
                                                            </View>
                                                            <View className="orderFood_list_detail_con">
                                                                食堂： {item.storeName}
                                                            </View>
                                                            <View className="orderFood_list_detail_wrap">
                                                                <View className="orderFood_list_detail_con">
                                                                    套餐名称：{item.packageName}
                                                                </View>
                                                                <View className="orderFood_list_detail_con">
                                                                    取餐点：{item.takeAddr}
                                                                </View>
                                                            </View>
                                                            <View className="orderFood_list_detail_con">
                                                                菜品明细：{item.dishDetail}
                                                            </View>
                                                            <View className="orderFood_list_detail_footer">
                                                                <View className="orderFood_list_detail_footer_amount">
                                                                    ¥{item.price.toFixed(2)} x
                                                                    <View
                                                                        className="orderFood_list_detail_footer_amount_wrap">
                                                                        <View
                                                                            className="orderFood_list_detail_footer_amount_wrap_son"/>
                                                                        <AtInputNumber
                                                                            type="digit"
                                                                            min={1}
                                                                            max={100}
                                                                            step={1}
                                                                            value={item.quantity}
                                                                            disabled={item.isModify === 'N' || !this.canClick}
                                                                            onChange={this.modifyQuantity.bind(this, item)}
                                                                        />
                                                                    </View>
                                                                </View>
                                                                {
                                                                    item.isModify === 'Y' ?
                                                                        <AtButton
                                                                            className="orderFood_list_detail_footer_button"
                                                                            onClick={this.cancelOrder.bind(this, orderList, index)}
                                                                        >退订</AtButton>
                                                                        :
                                                                        <View>
                                                                            已取餐份数：<View
                                                                            className="orderFood_list_detail_footer_takeCnt"
                                                                        >{item.takeCnt}</View>
                                                                        </View>
                                                                }
                                                            </View>
                                                        </View>
                                                    </View>
                                                ))
                                            }
                                        </View>
                                    </HxInfiniteScroll>

                                </View>
                                :
                                <View className="orderFood_scroll">
                                    <View className="orderFood_wrap">
                                        {
                                            menuHeadList.map(item =>
                                                <View key={item.date} className="orderFood_date">
                                                    <View
                                                        className="orderFood_date_header">{timeWeekPipe(item.menuDate)}</View>
                                                    {
                                                        item.mealTimeList.map(itemSon =>
                                                            <View className="orderFood_date_item"
                                                                  key={itemSon.mealTimeId}>
                                                                <View
                                                                    className="orderFood_date_item_left">{itemSon.mealTimeName}</View>
                                                                <View className="orderFood_date_item_right">
                                                                    {
                                                                        itemSon.orderList.length > 0 ?
                                                                            itemSon.orderList.map((itemOrder, index) =>
                                                                                <View
                                                                                    className="orderFood_date_item_right_con"
                                                                                    key={itemOrder.packageId}>
                                                                                    <View
                                                                                        className='orderFood_date_item_right_con_left'>
                                                                                        <View
                                                                                            className='packageName'
                                                                                            onClick={this.showDetail.bind(this, itemOrder)}>{itemOrder.packageName}</View>{itemOrder.quantity}份(¥{itemOrder.price})
                                                                                        <View
                                                                                            className='storeName'>{itemOrder.storeName}</View>{itemOrder.takeAddr}
                                                                                    </View>
                                                                                    <AtButton
                                                                                        className="hxButton xs_button"
                                                                                        disabled={itemSon.isModify === 'N'}
                                                                                        onClick={this.goDetail.bind(this, item.menuDate, itemSon, index)}
                                                                                    >更改</AtButton>
                                                                                </View>
                                                                            )
                                                                            :
                                                                            <View
                                                                                className="orderFood_date_item_right_con">
                                                                                <View
                                                                                    className='orderFood_date_item_right_con_no'>未订餐</View>
                                                                                <AtButton className="hxButton xs_button"
                                                                                          disabled={itemSon.isModify === 'N'}
                                                                                          onClick={this.goDetail.bind(this, item.menuDate, itemSon, -1)}
                                                                                >去订餐</AtButton>
                                                                            </View>
                                                                    }
                                                                </View>
                                                            </View>)
                                                    }
                                                </View>)
                                        }
                                    </View>
                                </View>
                    }

                </View>
            </HxPage>
        );
    }
}
